package com.begye.smartloan.apptest.sezhi.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.begye.smartloan.apptest.R
import org.json.JSONObject

class SeZhiTouXiangAdapter(var dataList: List<JSONObject>, val onClickAction: (Int) -> Unit) :
    RecyclerView.Adapter<SeZhiTouXiangAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.list_item_se_zhi_tou_xiang, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val listItemSeZhiTouXiangIcon: ImageView =
            view.findViewById(R.id.listItemSeZhiTouXiangIcon)

        private val listItemSeZhiTouXiangCheckBox: ImageView =
            view.findViewById(R.id.listItemSeZhiTouXiangCheckBox)


        @SuppressLint("SetTextI18n")
        fun bindData(position: Int, item: JSONObject) {

            val resId = item.optInt("resId", R.drawable.dres_119)
            listItemSeZhiTouXiangIcon.setImageResource(resId)

            val isChecked = item.optString("isChecked", "")
            if (isChecked == "YES") {
                listItemSeZhiTouXiangCheckBox.setImageResource(R.drawable.dres_118)
            } else {
                listItemSeZhiTouXiangCheckBox.setImageResource(R.drawable.dres_117)
            }

            listItemSeZhiTouXiangIcon.setOnClickListener {
                for (element in dataList) {
                    element.put("isChecked", "NO")
                }
                item.put("isChecked", "YES")
                onClickAction.invoke(position)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindData(position, dataList[position])
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}